const express = require('express');
const router = express.Router();

// 模拟延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 生成模拟路径规划数据
const generateRouteData = (origin, destination, strategy = 0, waypoints = '') => {
  const baseSteps = [
    {
      instruction: '从起点出发，沿花城大道向东行驶',
      orientation: '东',
      distance: '500',
      tolls: '0',
      toll_distance: '0',
      toll_road: '',
      polyline: '113.289405,23.013125;113.290405,23.013125'
    },
    {
      instruction: '右转进入珠江新城路',
      orientation: '南',
      distance: '800',
      tolls: '0',
      toll_distance: '0',
      toll_road: '',
      polyline: '113.290405,23.013125;113.290405,23.005125'
    },
    {
      instruction: '左转进入广州大道',
      orientation: '东',
      distance: '1200',
      tolls: '0',
      toll_distance: '0',
      toll_road: '',
      polyline: '113.290405,23.005125;113.302405,23.005125'
    },
    {
      instruction: '继续直行到达目的地',
      orientation: '东',
      distance: '2700',
      tolls: '0',
      toll_distance: '0',
      toll_road: '',
      polyline: '113.302405,23.005125;113.329405,23.005125'
    }
  ];

  let routeData = {
    success: true,
    data: {
      origin: origin,
      destination: destination,
      strategy: strategy,
      waypoints: waypoints,
      distance: '5.2',
      duration: '1200',
      tolls: '0',
      toll_distance: '0',
      steps: [...baseSteps],
      traffic: {
        status: '畅通',
        evaluation: '良好',
        expeditious: '0',
        congested: '0',
        blocked: '0',
        unknown: '0'
      }
    },
    message: '路径规划成功'
  };

  // 根据策略调整路径
  switch (parseInt(strategy)) {
    case 1: // 费用优先
      routeData.data.distance = '6.1';
      routeData.data.duration = '1400';
      routeData.data.steps[2].instruction = '选择免费道路，绕行一段距离';
      break;
    case 2: // 距离优先
      routeData.data.distance = '4.8';
      routeData.data.duration = '1100';
      routeData.data.steps[1].instruction = '选择最短路径，直接穿行';
      break;
    case 3: // 不走高速
      routeData.data.distance = '7.2';
      routeData.data.duration = '1600';
      routeData.data.steps[2].instruction = '避开高速公路，选择城市道路';
      break;
    case 4: // 躲避拥堵
      routeData.data.distance = '5.8';
      routeData.data.duration = '1300';
      routeData.data.steps[1].instruction = '避开拥堵路段，选择替代路线';
      break;
    case 5: // 多策略
      routeData.data.distance = '5.5';
      routeData.data.duration = '1250';
      routeData.data.steps[2].instruction = '综合考虑多种因素，选择最优路径';
      break;
  }

  return routeData;
};

// GET /api/route - 路径规划
router.get('/', async (req, res) => {
  try {
    const { origin, destination, strategy = 0, waypoints } = req.query;
    
    // 参数验证
    if (!origin || !destination) {
      return res.status(400).json({
        success: false,
        message: '缺少origin或destination参数'
      });
    }
    
    // 模拟网络延迟
    await delay(600);
    
    // 生成模拟数据
    const routeData = generateRouteData(origin, destination, strategy, waypoints);
    
    res.json(routeData);
  } catch (error) {
    console.error('路径规划API错误:', error);
    res.status(500).json({
      success: false,
      message: '路径规划失败',
      error: error.message
    });
  }
});

// GET /api/route/driving - 驾车路径规划
router.get('/driving', async (req, res) => {
  try {
    const { origin, destination, strategy = 0 } = req.query;
    
    if (!origin || !destination) {
      return res.status(400).json({
        success: false,
        message: '缺少origin或destination参数'
      });
    }
    
    await delay(500);
    
    const drivingData = {
      success: true,
      data: {
        origin: origin,
        destination: destination,
        strategy: strategy,
        distance: '5.2',
        duration: '1200',
        tolls: '0',
        fuel_cost: '15.6',
        steps: [
          {
            instruction: '从起点出发，沿花城大道向东行驶',
            distance: '500',
            duration: '120',
            polyline: '113.289405,23.013125;113.290405,23.013125'
          },
          {
            instruction: '右转进入珠江新城路',
            distance: '800',
            duration: '180',
            polyline: '113.290405,23.013125;113.290405,23.005125'
          }
        ]
      },
      message: '驾车路径规划成功'
    };
    
    res.json(drivingData);
  } catch (error) {
    console.error('驾车路径规划API错误:', error);
    res.status(500).json({
      success: false,
      message: '驾车路径规划失败',
      error: error.message
    });
  }
});

// GET /api/route/walking - 步行路径规划
router.get('/walking', async (req, res) => {
  try {
    const { origin, destination } = req.query;
    
    if (!origin || !destination) {
      return res.status(400).json({
        success: false,
        message: '缺少origin或destination参数'
      });
    }
    
    await delay(300);
    
    const walkingData = {
      success: true,
      data: {
        origin: origin,
        destination: destination,
        distance: '1.2',
        duration: '1800',
        steps: [
          {
            instruction: '从起点出发，沿花城大道向东步行',
            distance: '300',
            duration: '360',
            polyline: '113.289405,23.013125;113.290405,23.013125'
          },
          {
            instruction: '右转进入珠江新城路',
            distance: '500',
            duration: '600',
            polyline: '113.290405,23.013125;113.290405,23.005125'
          }
        ]
      },
      message: '步行路径规划成功'
    };
    
    res.json(walkingData);
  } catch (error) {
    console.error('步行路径规划API错误:', error);
    res.status(500).json({
      success: false,
      message: '步行路径规划失败',
      error: error.message
    });
  }
});

// GET /api/route/transit - 公交路径规划
router.get('/transit', async (req, res) => {
  try {
    const { origin, destination, date = new Date().toISOString().split('T')[0] } = req.query;
    
    if (!origin || !destination) {
      return res.status(400).json({
        success: false,
        message: '缺少origin或destination参数'
      });
    }
    
    await delay(800);
    
    const transitData = {
      success: true,
      data: {
        origin: origin,
        destination: destination,
        date: date,
        routes: [
          {
            id: 'route1',
            name: '地铁3号线',
            distance: '2.5',
            duration: '1800',
            cost: '3',
            steps: [
              {
                instruction: '步行到珠江新城地铁站',
                distance: '300',
                duration: '360'
              },
              {
                instruction: '乘坐地铁3号线',
                distance: '2.0',
                duration: '1200',
                line: '地铁3号线'
              },
              {
                instruction: '步行到目的地',
                distance: '200',
                duration: '240'
              }
            ]
          }
        ]
      },
      message: '公交路径规划成功'
    };
    
    res.json(transitData);
  } catch (error) {
    console.error('公交路径规划API错误:', error);
    res.status(500).json({
      success: false,
      message: '公交路径规划失败',
      error: error.message
    });
  }
});

module.exports = router; 